package shuishijie.suishijie.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;



import java.io.File;
import java.util.HashMap;
import java.util.Map;

import shuishijie.suishijie.PayActivity;
import shuishijie.suishijie.R;


/**
 * 自定义WebView实现，包含一定的业务处理
 */
public class CustomWebView extends LinearLayout {
    private static final String TAG = "CustomWebView";
    /**
     * 自定义WebView的Listener
     */
    private ICustomWebViewListener customWebViewListener;

    /**
     * 下接刷新Layout
     */
//    private SwipeRefreshLayout swipeLayout;

    /**
     * 系统WebView
     */
    private WebView systemWebView;

    /**
     * WebView加载出错Layout
     */
    private LinearLayout customWebViewErrorLayout;

    /**
     * 重新加载按扭
     */
    private Button customWebViewReloadBtn;

    /**
     * Url无权限加载提示Layout
     */
    private LinearLayout urlPermissionLayout;

    /**
     * 无权限URL展示TextView
     */
    private TextView urlPermissionText;

    /**
     * 是否在新窗口中打开URL
     */
    private boolean openNewWindow;

    /**
     * 网页加载是否出错
     */
    private volatile boolean isReceivedError;

    /**
     * 是否调用了onPageStarted/onReceivedError
     */
    private volatile boolean callStartPageOrReceivedError;

    /**
     * 是否调用了onReceivedError
     */
    private volatile boolean callReceivedError;

    /**
     * 是否允许显示加载出错UI
     */
    private boolean allowShowErrorUi = true;

    /**
     * 数据加载dialog
     */
    private Dialog loadingDialog;

//    private JsCallJava mJsCallJava = null;

    private ProgressBar progressbar;
    private boolean isProgressShow = true;

    public CustomWebView(Context context) {
        this(context, null);
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 允许显示加载出错UI
        allowShowErrorUi = true;

        LayoutInflater.
                from(context).inflate(R.layout.customwebview, this, true);

        // 初始化画面内容
        initView(context);
    }

    /**
     * 加载WebUrl
     *
     * @param url URL
     */
    public void loadUrl(String url) {
        if (checkUrlPermission(url)) {
            systemWebView.loadUrl(url);
        } else {
            urlPermissionText.setText(url);
            showUrlPermissionLayout();
        }
    }

    /**
     * 取得是否允许显示加载出错UI
     *
     * @return ture:允许显示加载出错UI, false:不允许显示加载出错UI
     */
    public boolean isAllowShowErrorUi() {
        return allowShowErrorUi;
    }

    /**
     * 设置是否允许显示加载出错UI
     *
     * @param allowShowErrorUi ture:允许显示加载出错UI, false:不允许显示加载出错UI
     */
    public void setAllowShowErrorUi(boolean allowShowErrorUi) {
        this.allowShowErrorUi = allowShowErrorUi;
    }

    /**
     * 取得是否在新窗口中打开URL
     *
     * @return 是否在新窗口中打开URL
     */
    public boolean isOpenNewWindow() {
        return openNewWindow;
    }
//
//    /**
//     * 设置是否在新窗口中打开URL
//     *
//     * @param jsCallJava 是否在新窗口中打开URL
//     */
//    public void setJsCallJava(JsCallJava jsCallJava) {
//        mJsCallJava = jsCallJava;
//    }

    /**
     * 设置是否在新窗口中打开URL
     *
     * @param openNewWindow 是否在新窗口中打开URL
     */
    public void setOpenNewWindow(boolean openNewWindow) {
        this.openNewWindow = openNewWindow;
    }

    /**
     * 设置是否显示progressbar
     *
     * @param isShow 是否显示progressbar
     */
    public void setIsShowProgressBar(boolean isShow) {
        this.isProgressShow = isShow;
    }

    /**
     * 设定自定义WebView的Listener
     *
     * @param customWebViewListener 自定义WebView的Listener
     */
    public void setCustomWebViewListener(ICustomWebViewListener customWebViewListener) {
        this.customWebViewListener = customWebViewListener;
    }

    /**
     * 取得系统WebView
     *
     * @return WebView
     */
    public WebView getSystemWebView() {
        return systemWebView;
    }

    /**
     * 判断当前网页是否加载失败
     *
     * @return true:失败,false:成功
     */
    public boolean isReceivedError() {
        return isReceivedError;
    }

    /**
     * 设置是否启用下拉刷新
     *
     * @param enabled 是否可用
     */
    public void enabledSwipeRefresh(boolean enabled) {
//        swipeLayout.setEnabled(enabled);
    }

    /**
     * 检查当前URL是否允许访问
     *
     * @param url URL
     * @return true:允许访问，false:不允许访问
     */
    private boolean checkUrlPermission(String url) {
        boolean blnRet = false;

//        if (!TextUtils.isEmpty(url) && (url.startsWith(Constant.ROOT_URL)
//                || url.startsWith(Constant.ROOT_DEV_URL))) {
        blnRet = true;
//        }

        return blnRet;
    }

    /**
     * 初始化画面内容
     */
    @SuppressLint("AddJavascriptInterface")
    private void initView(Context context) {
        // 查找画面各View对象
        systemWebView = (WebView) findViewById(R.id.systemWebView);
//        swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        customWebViewErrorLayout = (LinearLayout) findViewById(R.id.custom_webview_error_layout);
        customWebViewReloadBtn = (Button) findViewById(R.id.custom_webview_reload_btn);
        urlPermissionLayout = (LinearLayout) findViewById(R.id.url_permission_layout);
        urlPermissionText = (TextView) findViewById(R.id.url_permission_text);
        progressbar = (ProgressBar) findViewById(R.id.progress);
        if (systemWebView.isInEditMode()) {
            return;
        }

        // 设置Web相关设置
        try {
            WebSettings webSettings = systemWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setSupportZoom(false);
            // 设置此属性，可任意比例缩放
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setBuiltInZoomControls(true);
            webSettings.setDisplayZoomControls(false);
            webSettings.setNeedInitialFocus(false);
            webSettings.setSaveFormData(false);
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
            webSettings.setAppCacheEnabled(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setDatabaseEnabled(true);
            webSettings.setAllowFileAccess(true);

            // 禁用横向滚动条
            systemWebView.setHorizontalScrollBarEnabled(false);
            // 禁用相相竖向滚动条
            systemWebView.setVerticalScrollBarEnabled(false);

            //滚动条风格，为0指滚动条不占用空间，直接覆盖在网页上
            systemWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

            // copy from liveFragment
            File cacheFile = systemWebView.getContext().getExternalCacheDir();
            if (cacheFile == null) {
                cacheFile = systemWebView.getContext().getCacheDir();
            }
            webSettings.setAppCachePath(cacheFile.getAbsolutePath());
            webSettings.setAllowContentAccess(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                webSettings.setAllowUniversalAccessFromFileURLs(true);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }

//            systemWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

        } catch (Exception e) {
            // nothing
        }

        // 禁用长按复制功能
        systemWebView.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        systemWebView.setWebViewClient(new WebViewClientEx());
        systemWebView.setWebChromeClient(new WebChromeClientEx());
//        systemWebView.addJavascriptInterface(AppNativeApi.getInstance(), "appNative");

//        // 下拉刷新处理
//        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                // 重新刷新页面
//                systemWebView.reload();
//            }
//        });

        // 重新加载按扭处理
        customWebViewReloadBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: zhangrl
                if (true /*!CommonUtils.isFastDoubleClick()*/) {
                    try {
//                        loadingDialog = CommonUtils.createLoadingDialog(v.getContext());
//                        loadingDialog.show();
                    } catch (Exception ex) {
                        // nothing
                    }

                    // 重新刷新页面
                    if (isOpenNewWindow()) {
                        systemWebView.loadUrl(systemWebView.getUrl());
                    } else {
                        systemWebView.reload();
                    }
                }
            }
        });

        // 重新加载按扭点击效果
//        customWebViewReloadBtn.setOnTouchListener(new ViewOnTouchListener(1));
        systemWebView.clearHistory();

        // 设置SwipeLayoutView中包含的子ViewGroup
//        ((SwipeLayoutView) swipeLayout).setChildViewGroup(systemWebView);

        try {
            if (Build.VERSION.SDK_INT < 17) {
                systemWebView.removeJavascriptInterface("searchBoxJavaBridge_");
            }
        } catch (Exception ex) {
            // nothing
        }
    }

    /**
     * 判断当前无权限URL展示Layout是否显示
     *
     * @return true:显示中，false:未显示
     */
    public boolean isUrlPermissionLayoutVisible() {
        return urlPermissionLayout.getVisibility() == View.VISIBLE;
    }

    /**
     * 显示无权限URL展示Layout
     */
    public void showUrlPermissionLayout() {
        urlPermissionLayout.setVisibility(View.VISIBLE);
//        swipeLayout.setVisibility(View.GONE);
        customWebViewErrorLayout.setVisibility(View.GONE);
    }

    /**
     * 隐藏无权限URL展示Layout
     */
    public void hideUrlPermissionLayout() {
        if (isReceivedError()) {
            customWebViewErrorLayout.setVisibility(View.VISIBLE);
//            swipeLayout.setVisibility(View.GONE);
            systemWebView.setVisibility(View.GONE);
        } else {
//            swipeLayout.setVisibility(View.VISIBLE);
            systemWebView.setVisibility(View.VISIBLE);
            customWebViewErrorLayout.setVisibility(View.GONE);
        }

        urlPermissionLayout.setVisibility(View.GONE);
    }


    /**
     * 自定义WebView的Listener
     */
    public interface ICustomWebViewListener {
        /**
         * Notify the host application of a change in the document title.
         *
         * @param view  The WebView that initiated the callback.
         * @param title A String containing the new title of the document.
         */
        void onReceivedTitle(WebView view, String title);

        /**
         * 加载新URL时触发
         *
         * @param view WebView
         * @param url  URL
         */
        void onOverrideUrlLoading(WebView view, String url);
    }

    /**
     * 自定义WebViewClient实现
     */
    private class WebViewClientEx extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.i(TAG, "onPageStarted:" + url);
            if (!"about:blank".equals(url)) {
                callStartPageOrReceivedError = true;
            }

            if (Build.VERSION.SDK_INT >= 19) {
                systemWebView.getSettings().setLoadsImagesAutomatically(true);
            } else {
                systemWebView.getSettings().setLoadsImagesAutomatically(false);
            }

            try {
                view.removeJavascriptInterface("accessibility");
                view.removeJavascriptInterface("accessibilityTraversal");
            } catch (Exception ex) {
                // nothing
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!systemWebView.getSettings().getLoadsImagesAutomatically()) {
                systemWebView.getSettings().setLoadsImagesAutomatically(true);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.i(TAG, "onReceivedError2 start" + errorCode + ":" + description + " : " + failingUrl);

            view.loadDataWithBaseURL(null, "", "text/html", "UTF-8", failingUrl);
            callReceivedError = true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i(TAG, "loading: " + url);
            boolean blnRet = false;

            for (String key : urlLoadingOverrideListeners.keySet()) {
                if (url.startsWith(key)) {
                    return urlLoadingOverrideListeners.get(key).shouldOverrideUrlLoading(view, url);
                }
            }
            // 禁用相相竖向滚动条
            // systemWebView.setVerticalScrollBarEnabled(false);
            if (url.startsWith(WebView.SCHEME_TEL) || url.startsWith(WebView.SCHEME_MAILTO)
                    || url.startsWith(WebView.SCHEME_GEO)) {
                blnRet = true;
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                view.getContext().startActivity(intent);
//            } else if (url.contains(Constant.LONGIN_URL)) {
//                blnRet = true;
//                CommonUtils.logout();
//                Intent intent = new Intent(view.getContext(), LoginActivity.class);
//                view.getContext().startActivity(intent);
//            } else if (url.startsWith("talkingdata")) {
//
//                try {
//                    TalkingDataHTML.GetInstance().execute(view.getContext(), url, view);
//                } catch (Exception e) {
//
//                }
//                blnRet = true;
//            } else if (url.startsWith(ShopHTML.URL_PREFIX)) {
//                // 积分商城的js调用
//                try {
//                    ShopHTML.GetInstance().execute(view.getContext(), url, view);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                blnRet = true;
            } else if (!checkUrlPermission(url)) {
                // 当前URL无权限访问
                blnRet = true;
                urlPermissionText.setText(url);
                showUrlPermissionLayout();
            } else if (!isOpenNewWindow() || TextUtils.isEmpty(view.getUrl())) {
                //view.loadUrl(url);
            } else if (url.compareTo(view.getUrl()) == 0) {
                //view.reload();

            } else if (isOpenNewWindow()) {
                blnRet = true;
                Intent intent = new Intent(view.getContext(), WebBrowseActivity.class);
                intent.putExtra("mapSearch", true);
                intent.putExtra("url", url);
                view.getContext().startActivity(intent);
            }else if (url.contains("https://offline.gvg666.com/dist/index.html#/load/registerPay")) {
                Log.i(TAG, "loading: " + url);
                Intent intent =new Intent( getContext(),PayActivity.class);
                getContext().startActivity(intent);


            }

            return blnRet;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //    super.onReceivedSslError(view, handler, error);
            // 需要处理ssl网页
            handler.proceed();
        }
    }

    /**
     * 自定义WebChromeClient实现
     */
    public class WebChromeClientEx extends WebChromeClient {
//        private boolean isJsLoaded = false;

        @Override
        public void onReceivedTitle(WebView view, String title) {
            Log.i(TAG, "onReceivedTitle:" + title);
            super.onReceivedTitle(view, title);
            if (customWebViewListener != null && !TextUtils.isEmpty(view.getUrl())
                    && !view.getUrl().endsWith("//" + title)) {
                if (!isReceivedError && !callReceivedError) {
                    customWebViewListener.onReceivedTitle(view, title);
                } else {
                    customWebViewListener.onReceivedTitle(view, "");
                }
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            result.confirm();
            Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
//            if (mJsCallJava != null) {
//                result.confirm(mJsCallJava.call(view, message));
//            }
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            Log.i(TAG, "onProgressChanged: " + view.getUrl() + ":" + newProgress);
//            if (newProgress <= 25) {
//                isJsLoaded = false;
//            } else if (!isJsLoaded && newProgress >= 25 && mJsCallJava != null) {
//                // 为什么要在这里注入JS
//                // 1 OnPageStarted中注入有可能全局注入不成功，导致页面脚本上所有接口任何时候都不可
//                // 2 OnPageFinished中注入，虽然都会全局注入成功，但是完成时间有可能太晚，当页面在初始化调用接口函数时会等待时间过长
//                // 3 在进度变化时注入，刚好可以在上面两个问题中得到一个折中处
//                // 为什么是进度大于25%才进行注入，因为从测试看来只有进度大于这个数字页面才真正得到框架刷新加载，保100%注入成功
//                isJsLoaded = true;
//                systemWebView.loadUrl(mJsCallJava.getPreloadInterfaceJS());
//            }
            if (isProgressShow) {
                if (progressbar.getVisibility() == GONE)
                    progressbar.setVisibility(VISIBLE);
                progressbar.setProgress(newProgress);
            }
//            if (newProgress < 50) {
//                if (!swipeLayout.isRefreshing() && swipeLayout.isEnabled()) {
//                    swipeLayout.setRefreshing(true);
//                }
//            } else {
//                //隐藏进度条
//                swipeLayout.setRefreshing(false);
//            }

            if (newProgress == 100) {
                if (isProgressShow) {
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            progressbar.setVisibility(GONE);
                        }
                    }, 100);
                }
                if (callStartPageOrReceivedError) {
                    isReceivedError = callReceivedError;
                    Log.i(TAG, isReceivedError ? "加载异常" : "加载正常");

                    // 加载异常并要求显示异常画面的场合
                    if (isReceivedError && isAllowShowErrorUi()) {
                        customWebViewErrorLayout.setVisibility(View.VISIBLE);
                        systemWebView.setVisibility(View.GONE);
//                        swipeLayout.setVisibility(View.GONE);
                    }

                    // 加载正常的场合
                    if (!isReceivedError/* && swipeLayout.getVisibility() != View.VISIBLE*/) {
//                        swipeLayout.setVisibility(View.VISIBLE);
//                        swipeLayout.invalidate();
                        customWebViewErrorLayout.setVisibility(View.GONE);
                        systemWebView.setVisibility(View.VISIBLE);
                    }

                    if (!isReceivedError && customWebViewListener != null && !TextUtils.isEmpty(systemWebView.getUrl())) {
                        customWebViewListener.onOverrideUrlLoading(view, systemWebView.getUrl());
                    }
                }

                try {
                    if (loadingDialog != null) {
                        loadingDialog.cancel();
                        loadingDialog = null;
                    }
                } catch (Exception ex) {
                    // nothing
                }
                callReceivedError = false;
                callStartPageOrReceivedError = false;
            }
        }

    }

    private Map<String, UrlLoadingOverrideListener> urlLoadingOverrideListeners = new HashMap<>();

    public void addUrlLoadingOverrideListener(String urlPrefix, UrlLoadingOverrideListener l) {
        if (l != null) {
            urlLoadingOverrideListeners.put(urlPrefix, l);
        } else if (!TextUtils.isEmpty(urlPrefix)) {
            urlLoadingOverrideListeners.remove(urlPrefix);
        }
    }

    public static interface UrlLoadingOverrideListener {
        public boolean shouldOverrideUrlLoading(WebView view, String url);
    }

}
